package com.itheima.controller;


import com.github.pagehelper.PageInfo;
import com.itheima.domain.User;
import com.itheima.mapper.UserMapper;
import com.itheima.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/user")
public class UserController {

    //引入UserService
    @Autowired
    private UserService userService;

    @RequestMapping("/login")
    public String login(String email, String password) throws Exception {
        System.out.println(email + "11" + password);
//        System.out.println(111);
       User user = userService.findEmailAndPwd(email, password);
        if (user != null) {
            return "main";
        } else {
            return "login";
        }
    }
    @RequestMapping("/list")
    public String list(@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,
                       @RequestParam(value = "pageSize",defaultValue = "3")Integer pageSize,
                       Model model)throws Exception{
        List<User> list=userService.findAll(pageNum,pageSize);
        //分页处理
        PageInfo<User> pageInfo=new PageInfo<User>(list);
        model.addAttribute("pageInfo",pageInfo);
        return "list";
    }

    @RequestMapping("/city")
    @ResponseBody
    public List<User> city() throws Exception {
        System.out.println(1111);
        List<User> list=userService.findAll();

        return list;
    }
    @RequestMapping("/add")
    public String add(User user) throws Exception {
        System.out.println(user);
        userService.add(user);
        return "forward:list";

    }
    @RequestMapping("/toUpdate")
    public String toUpdate(String id,Model model) throws Exception {
        User user = userService.findById(id);
        model.addAttribute("user", user);
        return "update";
    }


    @RequestMapping("/updateByUser")
    public String updateByUser(User user) throws Exception {
        userService.update(user);


        return "forward:list";
    }
    @RequestMapping("/deleteById")
    public String deleteById(String id) throws Exception {
        userService.deleteById(id);
        return "forward:list";
    }

}
